import 'dart:io';

import 'package:bot_toast/bot_toast.dart';
import 'package:dear_lottery/tools/models/DL_DataViewModel.dart';
// import 'package:euromillions/Home/EJ_HomePageVC.dart';
// import 'package:euromillions/Launch/EJ_TabbarPageVC.dart';
// import 'package:euromillions/tools/EJ_config.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../tools/KaL_Config.dart';
import '../tools/FL_CustomLoading.dart';
import '../tools/models/KL_keralaLottoDataModel.dart';
import '../tools/models/KaL_DataViewModels.dart';
// import '../tools/sqLite/EJ_mySQLite.dart';
import 'package:connectivity_plus/connectivity_plus.dart';

import '../tools/sqLite/EJ_mySQLite.dart';
import 'EJ_TabbarPageVC.dart';

class EJLaunchPage extends StatefulWidget {
  const EJLaunchPage({super.key});

  @override
  State<EJLaunchPage> createState() => _EJLaunchPageState();
}

class _EJLaunchPageState extends State<EJLaunchPage> {
  ///是否请求失败
  bool _requestedStates = true;
  List<ConnectivityResult> _EJconnectionStatus = [ConnectivityResult.none];
  final Connectivity _connectivity = Connectivity();

  _configData() async {
    //启动加载数据
    // _requestedStates = await KaL_DataViewModels().getData(100);
    // await KL_keralaLottoDataModel().getNextDrawnData();
    // _requestedStates = await KL_keralaLottoDataModel().getAllData();

    DL_DataViewModel().getNextDrawnData();
    _requestedStates = await DL_DataViewModel().getData();

    if (_requestedStates) {
      _PushToHome();
    } else {
      // requestedStates = false;
      setState(() {});
    }
    BotToast.closeAllLoading();
  }

  _loadSQlite() async {
    //加载数据库
    await EJ_mySQlite.forFeature();
  }

  _PushToHome() {
    var _duration = const Duration(milliseconds: 300);
    Future.delayed(_duration, _HomePage);
  }

  _HomePage() {
    // Navigator.of(context).pushReplacement(
    //     MaterialPageRoute(builder: (context) => EJHomePageVC()));
    Navigator.of(context).pushReplacement(
        MaterialPageRoute(builder: (context) => EJTabbarPageVC()));
  }

  //iOS 监听网络授权
  Future<void> _initConnectivity() async {
    late List<ConnectivityResult> result;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      result = await _connectivity.checkConnectivity();
    } on PlatformException catch (e) {
      debugPrint('Couldn\'t check connectivity status,$e');
      return;
    }
    if (!mounted) {
      return Future.value(null);
    }

    return EJ_updateConnectionStatus(result);
  }

  Future<void> EJ_updateConnectionStatus(
      List<ConnectivityResult> result) async {
    _EJconnectionStatus = result;
    // debugPrint("_connectionStatus---$_EJconnectionStatus");
    ConnectivityResult res = _EJconnectionStatus[0];
    if (res != ConnectivityResult.none) {
      _configData();
    } else {
      // requestFail = true;
      // setState(() {});
      _initConnectivity();
      setState(() {});
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    BotToast.showCustomLoading(toastBuilder: (cancelFunc) {
      return FLCustomLoading(
        themeColor: KaL_Config.KaL_themeColor_HL,
      );
    });

    if (Platform.isIOS) {
      _initConnectivity();
    } else {
      _configData();
    }

    _loadSQlite();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: double.infinity,
        width: double.infinity,
        // color: KaL_Config.KaL_MainColor,
        decoration: BoxDecoration(
          gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                KaL_Config.KaL_themeColor_HL,
                KaL_Config.KaL_themeColor_N
              ]),
        ),
        // color: Colors.white,
        child: Stack(
          alignment: Alignment.center,
          children: [
            Positioned(
              // bottom: 30,
              child: Container(
                height: 130,
                width: 225,
                child: Image.asset(
                  'assets/sys_imgs/DearLottery Logo.png',
                  // width: 120,
                  // height: 120,
                ),
              ),
            ),
            _requestedStates
                ? Container()
                : Positioned(
                    bottom: 40,
                    child: Column(
                      children: [
                        const Text(
                          'SOMETHING ERROR!!!',
                          style: TextStyle(color: Colors.white),
                        ),
                        const SizedBox(height: 10),
                        OutlinedButton(
                            style: ButtonStyle(
                              side: MaterialStateProperty.all(const BorderSide(
                                color: Colors.white, // 边框颜色
                                width: 1.0, // 边框宽度
                              )),
                            ),
                            onPressed: () {
                              // configData();
                            },
                            child: const Text(
                              'REFRESH',
                              style: TextStyle(color: Colors.white),
                            ))
                      ],
                    )),
          ],
        ),
      ),
    );
  }
}
